package com.example.start;

import com.example.entity.User;
import sun.reflect.generics.tree.VoidDescriptor;

import java.util.Optional;

/**
 * @Classname Start
 * @Description TODO
 * @Date 2021/12/2 10:12
 * @Created by silence(dxs)
 */
public class Start {
    public static void main(String[] args) {
        User user = new User("zhangsan", 12);
        User user1 = null;
//        Start.optionalOf(user, user1);
//        Start.optionalOfNullable(user, user1);
//        Start.ofElseAndOfElseGet(user, user1);
        Start.optionalMap(user);

    }

    //1. Optional.of(xx) 返回一个optional 若xx为空则抛空指针异常
    public static void  optionalOf(User user,User user1){
        Optional<User> userOptional = Optional.of(user);
        System.out.println(userOptional.get());  //正常
        Optional<User> userOptional1 = Optional.of(user1);
        System.out.println(userOptional1.get()); // 异常

    }

    //2. Optional.ofNullable(xx) 返回optional 若xx为空则返回null不抛异常
    public static void optionalOfNullable(User user,User user1){
        Optional<User> optionalUser = Optional.ofNullable(user);
        System.out.println(optionalUser.get());
        Optional<User> optionalUser1 = Optional.ofNullable(user1);
        System.out.println(optionalUser1.isPresent());
    }

    // 3. orElse 和 orElse 区别：Optional.ofNullable(xx)当xx不为空时orElse还是会执行，后者反之
    public static void  ofElseAndOfElseGet(User user,User user1){
        User wang = Optional.ofNullable(user1).orElse(new User("王五", 12));
        System.out.println(wang);
        User zhao = Optional.ofNullable(user1).orElseGet(() -> {
            return new User("赵六", 13);
        });
        System.out.println(zhao);

    }
    // 4.map 返回对象的属性的optional对象
    public static void optionalMap(User user){
        Optional<String> optional = Optional.ofNullable(user).map((item) -> {
            return user.getName();
        });
        System.out.println(optional.get());
    }
    // 5.实际开发中的对象判空
    public static void fact(User user) throws Throwable {
      Optional.ofNullable(user).ifPresent((item)->{
          // user不为空的操作
      });
      Optional.of(user).filter(item->item.getName()!=null).ifPresent(item->{
          // todo
      });
      Optional.of(user).filter(item->item.getName()==null).ifPresent(item->{
          // todo
      });
        String s = Optional.of(user).map(item -> item.getName()).get();
    }
}
